package com.tanhua.dubbo.huanxin.service;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tanhua.dubbo.huanxin.config.HuanXinConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class TokenService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String REDIS_KEY = "HX_TOKEN";

    @Autowired
    private HuanXinConfig huanXinConfig;

    /*
     * 获取token，先从redis中获取，如果没有，再去环信接口获取
     * */
    public String getToken() {
        String token = this.redisTemplate.opsForValue().get(REDIS_KEY);
        if (StrUtil.isNotEmpty(token)) {
            return token;
        }
        return refreshToken();
    }

    /**
     * 刷新token，请求环信接口，将token存储到redis中
     *
     * @return
     */
    public String refreshToken() {
        String url = StrUtil.format("{}/{}/{}/token",
                this.huanXinConfig.getUrl(),
                this.huanXinConfig.getOrgName(),
                this.huanXinConfig.getAppName());
        Map<String, Object> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", this.huanXinConfig.getClientId());
        param.put("client_secret", this.huanXinConfig.getClientSecret());

        HttpResponse response = HttpRequest.post(url)
                .timeout(5000)
                .body(JSONUtil.toJsonStr(param)) //请求体
                .execute();

        if (response.isOk()){
            //获取token成功
            String body = response.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String token = jsonObject.getStr("access_token");

            //提前一小时失效
            Long expires = jsonObject.getLong("expires_in") - 3600;

            //将token存储到redis中
            this.redisTemplate.opsForValue().set(REDIS_KEY, token, expires, TimeUnit.SECONDS);

            return token;
        }
        //获取token出错
        return null;
    }
}
